package com.heima.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojo.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.BCrypt;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    /**
     * 登录接口
     *   二合一，用户登录也是有游客登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        //1. 判断用户登录方式-正常登录
        if(StringUtils.isNotBlank(dto.getPhone()) && StringUtils.isNotBlank(dto.getPassword())){

            //2. 查询用户是否存在
            ApUser apUser = this.lambdaQuery().eq(ApUser::getPhone, dto.getPhone()).one();
            if(apUser == null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }

            //3. 密码校验
            String dtoPassword = dto.getPassword();
            String apUserPassword = apUser.getPassword();
            boolean result = BCrypt.checkpw(dtoPassword, apUserPassword);
            if (!result){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }

            //4. 判断用户状态是否正确
            Boolean status = apUser.getStatus();
            if(status){
                return ResponseResult.errorResult(AppHttpCodeEnum.INVALID_STATUS);
            }

            //5. 生成token
            String token = AppJwtUtil.getToken(apUser.getId().longValue());
            Map hashMap = new HashMap();
            hashMap.put("token",token);

            apUser.setPassword("");
            hashMap.put("user",apUser);
            return ResponseResult.okResult(hashMap);

        } else{
            //6. 用户登录-游客登录
            String token = AppJwtUtil.getToken(0L);
            Map hashMap = new HashMap();
            hashMap.put("token",token);
            return ResponseResult.okResult(hashMap);
        }
    }

    /**
     * 根据用户id获取用户实体
     *
     * @param userId
     * @return
     */
    @Override
    public ResponseResult<ApUser>findUserById(Integer userId) {
        ApUser apUser = getById(userId);
        return ResponseResult.okResult(apUser);
    }
}
